package cn.minimelon.api.service.module.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjUtil;
import cn.minimelon.api.constant.UserConstants;
import cn.minimelon.api.domain.module.po.DataArea;
import cn.minimelon.api.domain.module.vo.DataModelVO;
import cn.minimelon.api.exception.ServiceException;
import cn.minimelon.api.mapper.module.DataAreaMapper;
import cn.minimelon.api.service.module.IDataAreaService;
import cn.minimelon.api.service.module.IDataModelService;
import org.apache.ibatis.solon.annotation.Db;
import org.noear.solon.annotation.Component;
import org.noear.solon.annotation.Inject;

import java.util.List;

@Component
public class DataAreaServiceImpl implements IDataAreaService {
    @Db
    private DataAreaMapper areaMapper;

    @Inject
    IDataModelService modelService;

    @Override
    public List<DataArea> selectList(DataArea dataArea) {
        return areaMapper.selectEntityList(dataArea);
    }

    @Override
    public DataArea selectById(String uid) {
        DataArea dataArea = new DataArea();
        dataArea.setUid(uid);
        return areaMapper.selectEntity(dataArea);
    }

    @Override
    public String checkCodeUnique(DataArea dataArea) {
        String uid = ObjUtil.isNull(dataArea.getUid()) ? "" : dataArea.getUid();
        DataArea info = areaMapper.selectByCode(dataArea.getCode());
        if (ObjUtil.isNotNull(info) && !uid.equals(info.getUid())) {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    @Override
    public int insert(DataArea dataArea) {
        return areaMapper.insert(dataArea);
    }

    @Override
    public int update(DataArea dataArea) {
        return areaMapper.updateById(dataArea);
    }

    @Override
    public int deleteById(String uid) {
        DataArea area = this.selectById(uid);
        DataModelVO model = new DataModelVO();
        model.setAreaCode(area.getCode());
        List<DataModelVO> list = modelService.selectList(model);
        if (CollUtil.isNotEmpty(list)) {
            throw new ServiceException(String.format("%s主题存在数据模型不能删除", area.getName()));
        }
        return areaMapper.deleteById(uid);
    }
}
